//
//  BaseWebVC.m
//  EPTool
//
//  Created by guoshiqing on 2018/4/24.
//  Copyright © 2018年 云数动能科技. All rights reserved.
//

#import "BaseWebVC.h"
#import "UIView+DDAddition.h"
#import "ErrorCode.h"
#import "Message.h"

#define kProgressViewHeight    2.f

@interface BaseWebVC ()
@property (nonatomic, assign) BOOL wasLoaded;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) CGFloat progress;
@end

@implementation BaseWebVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = self.titleName;
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 设置导航
    [self createBackButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 添加webView
    [self addWebView];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[self.wvContentView configuration].userContentController removeScriptMessageHandlerForName:@"tokenChanged"];
}

#pragma mark - 清理url缓存
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self destroyMe];
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (WKWebView *)wvContentView
{
    if (!_wvContentView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.selectionGranularity = WKSelectionGranularityCharacter;
        WKUserContentController *control = [[WKUserContentController alloc] init];
//        [control addScriptMessageHandler:self name:@"getLocation"];
        config.userContentController = control;
        
        _wvContentView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_CONTENT_HEIGHT) configuration:config];
        _wvContentView.navigationDelegate = self;
        [[_wvContentView configuration].userContentController addScriptMessageHandler:self name:@"tokenChanged"];
    }
    return _wvContentView;
}

- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, kProgressViewHeight);
        _progressView.progressTintColor = [EPColor epColor_Blue];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}

#pragma mark - 进度变化处理
- (void)setProgress:(CGFloat)progress
{
    _progress = progress;
    if (self.progressView.alpha == 0) {self.progressView.alpha = 1;}
    [self.progressView setProgress:progress animated:YES];
    if (progress >= 1) {
        
        [UIView animateWithDuration:0.8 animations:^{
            self.progressView.alpha = 0;
        } completion:^(BOOL finished) {
            self.progressView.progress = 0;
        }];
    }
}

#pragma mark - 添加一个webview
- (void)addWebView
{
    [self.view addSubview:self.wvContentView];
    
    // 插入进度条并监听进度变化
    [self.view insertSubview:self.progressView aboveSubview:self.wvContentView];
    [self.wvContentView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

    // 添加JS调用的方法
//    [[self.wvContentView configuration].userContentController addScriptMessageHandler:self name:@"getLocation"];
    /* !!! 很容易引起循环引用，需要释放掉  viewWillDisappear或者其他中  !!! */
//    [[self.wvContentView configuration].userContentController removeScriptMessageHandlerForName:@"getLocation"];
    
    // 设置webview的url
//    if ([StringUtil isNotEmpty:self.bundleFilePath]) {
//        [_wvContentView loadHTMLString:self.url baseURL:[NSURL fileURLWithPath:self.bundleFilePath]];
//    } else {
//        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
//        [_wvContentView loadRequest:request];
//    }
    [self loadWebView];
    // 标题
//    if (!self.titleName || self.titleName.length == 0) {
//        [_wvContentView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
//    }
}

- (void)addPlaceholerView
{
    self.placeholderView.hintImageName = @"default_link";
    self.placeholderView.hintText = NSLocalizedString(@"TheLinkIsOver", @"该链接已失效");
    self.placeholderView.height = UI_CONTENT_HEIGHT;
    [self.view addSubview:self.placeholderView];
    self.placeholderView.hidden = NO;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progress = self.wvContentView.estimatedProgress;
    }
    else if ([keyPath isEqualToString:@"title"])
    {
        if (object == _wvContentView) {
            self.title = _wvContentView.title;
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - 设置导航栏上的按钮
- (void)btnBackClick:(id)sender
{
    if (_wvContentView.canGoBack)
    {
        [_wvContentView goBack];
    }
    else
    {
        [self dismissVC];
    }
}

#pragma mark - 提供给js调用的关闭接口
- (void)dismissVC4JS
{
    [self dismissVC];
}

- (void)dismissVC
{
    [self dismissViewControllerAnimated:NO completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

//- (void)dealloc {
//    [self destroyMe];
//}

#pragma mark - wkWebViewDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    // 开始加载
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    // 加载完成
    self.placeholderView.hidden = YES;
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    // 没有网络
    if (CODE_AFN_NOWORK == error.code) {
        WEAKSELF
        [self showNetUnreachableImageName:@"" andBlock:^{
            [weakSelf loadWebView];
        }];
        return;
    }
    // 连接异常
    if (CODE_AFN_NOWORK == error.code) {
        WEAKSELF
        [self showNetFailureImageName:@"" andBlock:^{
            [weakSelf loadWebView];
        }];
        return;
    }
    [self addPlaceholerView];
    self.title = NSLocalizedString(@"TheLinkIsOver", @"该链接已失效");
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        NSURLRequest *request = [NSURLRequest requestWithURL:navigationAction.request.URL];
        [webView loadRequest:request];
    }
    
    // 私有协议都直接使用外部跳转
    NSString *strUrl = [navigationAction.request.URL absoluteString];
    if ((NSNotFound == [strUrl rangeOfString:@"http://"].location) &&
        (NSNotFound == [strUrl rangeOfString:@"https://"].location)) {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}

#pragma mark -- WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //JS调用OC方法
    NSString *method = message.name;
    NSDictionary *dic = message.body;
    if ([method isEqualToString:@"tokenChanged"]) {
        [self tokenChanged:dic];
    }
}

- (void)tokenChanged:(NSDictionary *)error
{
    int code = (int)error[@"code"];
    if ((C_BeKick == code) || (C_LoseLogin == code) || (C_Invalid == code)) {
        [NotificationHelp postNotification:NotificationGo2LoginVC object:error[@"msg"]];
        return;
    }
    return [ToastView showMsg:error[@"msg"]];
}

- (void)destroyMe {
    
    if (_wvContentView) {
//        if (!self.titleName || self.titleName.length == 0) {
//            [_wvContentView removeObserver:self forKeyPath:@"title"];
//        }
        [_wvContentView removeObserver:self forKeyPath:@"estimatedProgress"];
        [_wvContentView loadHTMLString:@"" baseURL:nil];
        [_wvContentView stopLoading];
        _wvContentView.navigationDelegate = nil;
        _wvContentView.scrollView.delegate = nil;
        [_wvContentView removeAllSubviews];
        [_wvContentView removeFromSuperview];
        [[NSURLCache sharedURLCache] removeAllCachedResponses];
        _wvContentView = nil;
    }
}


#pragma mark - 加载
- (void)loadWebView
{
    // 设置webview的url
    if ([StringUtil isNotEmpty:self.bundleFilePath]) {
        [self.wvContentView loadHTMLString:self.url baseURL:[NSURL fileURLWithPath:self.bundleFilePath]];
    } else {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
        [self.wvContentView loadRequest:request];
    }
}

@end
